package com.study.component;

import cn.hutool.core.thread.ThreadUtil;
import com.study.dto.Student;
import com.study.dto.SubDTO;
import com.study.utils.Consts;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzi
 * 2024/3/25 23:33
 */
@Slf4j
@Component
public class Subscribe {
    @Autowired
    private RedissonClient redissonClient;

    @PostConstruct
    public void subscribe() {
        RTopic rTopic = redissonClient.getTopic(Consts.TopicName);
        rTopic.addListener(SubDTO.class, new MessageListener<SubDTO>() {
            /**
             * 接受订阅的消息
             * @param channel of topic
             * @param msg     topic message
             */
            @Override
            public void onMessage(CharSequence channel, SubDTO msg) {
                log.info("接受到消息主题={}，内容={}", channel, msg);
                msg.setConsumerDateTime(LocalDateTime.now()).setConsumer(true);
            }
        });


        //监听的实体不一样,返回的数据不一样
        rTopic.addListener(Student.class, (channel, msg) -> {
            log.info("接受到😄|stu|消息主题={}，内容={}", channel, msg);
            ThreadUtil.sleep(2, TimeUnit.SECONDS);
        });
    }

}
